<template>
	<vxe-grid ref='vxeGridRef' v-bind='gridConfig'>
		<template v-slot:form>
			<n-flex align='center' justify='center'>
				<n-form-item label='图标名' label-placement='left' :show-feedback='false'>
					<n-input v-model:value='gridConfig["formConfig"]!["data"]["name"]' type='text'
							 placeholder='请输入图标名' clearable/>
				</n-form-item>
				<n-button round strong :bordered='false'
						  type='success' @click='initGrid(gridConfig["formConfig"]!["data"])'>
					搜索
				</n-button>
				<n-button round strong :bordered='false'
						  type='info' @click='reset'>
					重置
				</n-button>
			</n-flex>
		</template>
		<template v-slot:toolbar_buttons>
		</template>
		<template v-slot:toolbar_tools>
			<div class='vxe-custom--wrapper'>
				<n-button circle @click='initGrid(gridConfig.formConfig?.data)'>
					<template v-slot:icon>
						<ClassIcon icon-class='fa fa-refresh'/>
					</template>
				</n-button>
			</div>
		</template>
		<template v-slot:svg_icon='{row}'>
			<SvgIcon :icon-type='props.iconType' :icon-class='row.value'/>
		</template>
		<template v-slot:operate='{row}'>
			<n-button round strong class='clipboardClass'
					  @click='copyToClipboard(row)'>
				<template v-slot:icon>
					<ClassIcon icon-class='fa fa-copy'/>
				</template>
			</n-button>
		</template>
	</vxe-grid>
</template>
<script setup lang='ts'>
import { defineAsyncComponent, onMounted, reactive, ref } from 'vue';
import { VxeGridInstance, VxeGridProps } from 'vxe-table';
import { VxeUI, VxeGrid } from '@/config/vxe/index.ts';
import ClipboardJs from 'clipboard';
const SvgIcon = defineAsyncComponent(() => import('@/components/customComponents/icon/SvgIcon.vue'));
const ClassIcon = defineAsyncComponent(() => import('@/components/customComponents/icon/ClassIcon.vue'));
const props = defineProps({
	iconType : {
		type     : String,
		required : true
	},
	iconData : Array<Record<string, any>>
});
// @ts-ignore
const gridConfig = reactive<VxeGridProps>({
	loading        : false,
	keyField       : 'name',
	height         : 'auto',
	align          : 'center',
	keyboardConfig : { isArrow : true },
	pagerConfig    : {
		currentPage : 1,
		pageSize    : 1000,
		total       : 0
	},
	toolbarConfig  : {
		custom : {
			icon : 'fa fa-cog'
		}
	},
	formConfig     : {
		data : {
			name : null
		}
	},
	columns        : [
		{
			field    : 'name',
			title    : '图标名称',
			sortable : true
		},
		{
			field : 'value',
			title : '图标样子',
			slots : {
				// 使用 JSX 渲染
				default : 'svg_icon'
			}
		},
		{
			title        : '操作',
			showOverflow : 'tooltip',
			slots        : {
				// 使用 JSX 渲染
				default : 'operate'
			}
		}
	],
	data           : [],
	// @ts-ignore
	onPageChange : async (params: any) => changePage(params)
});
const vxeGridRef = ref<VxeGridInstance>();
onMounted(() => {
	initGrid(gridConfig['formConfig']);
});
/**
 * 初始化表格
 * @param queryParams 查询参数
 */
const initGrid = async (queryParams: any) => {
	gridConfig['loading'] = true;
	vxeGridRef.value?.clearCurrentRow();
	vxeGridRef.value?.clearCurrentColumn();
	// 过滤出符合查询条件的图标
	if (queryParams.name) {
		let tempData = props.iconData?.filter(
			item => item.name.toLowerCase().includes(queryParams.name.toLowerCase())
		);
		if (tempData && Array.isArray(tempData) && tempData.length) {
			tempData = tempData.filter(
				(item, index) => {
					const limit1 = ((gridConfig!['pagerConfig']!['currentPage'] as number - 1) * (gridConfig!['pagerConfig']!['pageSize'] as number));
					const limit2 = ((gridConfig!['pagerConfig']!['currentPage'] as number) * (gridConfig!['pagerConfig']!['pageSize'] as number));
					return index >= limit1 && index <= limit2;
				}
			);
		}
		gridConfig['pagerConfig']!['total'] = tempData?.length;
		gridConfig['pagerConfig']!['currentPage'] = 1;
		gridConfig['data'] = tempData;
	} else {
		const tempData = props.iconData?.filter(
			(item, index) => {
				const limit1 = ((gridConfig!['pagerConfig']!['currentPage'] as number - 1) * (gridConfig!['pagerConfig']!['pageSize'] as number));
				const limit2 = ((gridConfig!['pagerConfig']!['currentPage'] as number) * (gridConfig!['pagerConfig']!['pageSize'] as number));
				return index > limit1 && index <= limit2;
			}
		);
		gridConfig['pagerConfig']!['total'] = props.iconData?.length;
		gridConfig['data'] = tempData;
	}
	gridConfig['loading'] = false;
};
/**
 * 清空查询条件
 */
const reset = () => {
	gridConfig['formConfig']!['data'] = {
		name : null
	};
	initGrid(gridConfig['formConfig']!['data']);
};
/**
 * 切换分页
 * @param currentPage 当前页码
 * @param pageSize 一页的数量
 */
const changePage = async ({ currentPage, pageSize }: { currentPage: number, pageSize: number }) => {
	gridConfig['pagerConfig']!['currentPage'] = currentPage;
	gridConfig['pagerConfig']!['pageSize'] = pageSize;
	await initGrid(gridConfig['formConfig']);
};
/**
 * 复制到粘贴板
 */
const copyToClipboard = async (rowData: any) => {
	// <SvgIcon :icon-type='props.iconType' :icon-class='row.value'/>
	/*let template = `<SvgIcon icon-type='${props['iconType']}' icon-class='${rowData['value']}'/>`;
	 // 该代码仅限于https和localhost下使用,http下应该使用其他方式
	 navigator.clipboard.writeText(template).then(() => {
	 console.log(template);
	 VxeUI.modal.message({
	 content : '喵~复制完毕ra~',
	 status  : 'success',
	 id      : 'copySuccessMessage'
	 });
	 }).catch(error => {
	 VxeUI.modal.message({
	 content : '你的浏览器或其他东西阻止了复制!',
	 status  : 'warning',
	 id      : 'failedMessage'
	 });
	 });*/
	// 判断浏览器是否支持
	if (ClipboardJs.isSupported()) {
		// 虽然ClipboardJs支持直接提供标签的方式,但是在列表环境下clipboardRef.value.$el并不能起效果
		const clipboard = new ClipboardJs('.clipboardClass', {
			action : (elem: Element) => 'copy',
			text   : (elem: Element): string => {
				return `<SvgIcon icon-type='${props['iconType']}' icon-class='${rowData['value']}'/>`;
			}
		});
		clipboard.on('success', (args: any[]) => {
			VxeUI.modal.message({
				content : '喵~复制完毕ra~',
				status  : 'success',
				id      : 'copySuccessMessage'
			});
			clipboard.destroy();
		});
		clipboard.on('error', (args: any[]) => {
			VxeUI.modal.message({
				content : '你的浏览器或其他东西阻止了复制!',
				status  : 'warning',
				id      : 'failedMessage'
			});
			clipboard.destroy();
		});
	} else {
		VxeUI.modal.message({
			content : '你的浏览器不支持复制!',
			status  : 'warning',
			id      : 'failedMessage'
		});
	}
};
</script>
<style scoped lang='scss'>
.icons-grid-container{
	box-sizing :border-box;
	margin     :0;
	padding    :0;
	border     :0;
	height     :100%;
	width      :100%;
}
</style>